package com.shiguiwu.springmybatis.spring.aop.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @description: callbak
 * 1. Cglib根据父类,Callback, Filter 及一些相关信息生成key
 * 2. 然后根据key 生成对应的子类的二进制表现形式
 * 3. 使用ClassLoader装载对应的二进制,生成Class对象,并缓存
 * 4. 最后实例化Class对象,并缓存
 * @author: stone
 * @date: Created by 2021/5/18 19:54
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.aop.cglib
 */
public class CglibCallbackTest {

    interface Service1 {
        void m1();
    }


    interface Service2 {
        void m2();
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();

        //设置代理对象需要实现的接口
        enhancer.setInterfaces(new Class[]{Service1.class, Service2.class});

        //通过Callback来对被代理方法进行增强
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("执行的方法：--->" + method.getName());
                return null;
            }
        });

        Object proxy = enhancer.create();

        if (proxy instanceof Service1) {
            ((Service1) proxy).m1();
        }

        if (proxy instanceof Service2) {
            ((Service2) proxy).m2();

        }

        System.out.println(proxy.getClass());


    }


}
